/*
 * File Name：ScanImageActivity.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ScanImageActivity.java
 * Modify By：bin
 * Modify Date：2015年1月16日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.RectF;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.TextView;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.adapter.ImagePagerAdapter;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.BaseIntentValue;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.widget.ScanImageBottom;
import com.ciwong.mobilelib.widget.ScanImageTitle;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;

/**
 * 查看图片
 *
 * @author bin
 * @version ciwong v.1.0 2015年1月16日
 * @since ciwong v.1.0
 */
public class ScanImageActivity extends BaseActivity {
    /**
     * 图片URL地址
     */
    public static final String IMAGE_URLS = "IMAGE_URLS";

    /**
     * 选中项索引
     */
    public static final String CURRENT_INDEX = "CURRENT_INDEX";

    /**
     * 显示类型
     */
    public static final String INTENT_FLAG_TYPE = "type";

    /**
     * 操作类型
     */
    public static final String INTENT_FLAG_ACTION = "action";

    /**
     * 拍一拍文件路径，标示
     */
    public static final String INTENT_FLAG_P1P_PATH = "p1p_path";

    /**
     * 跳转码
     */
    public static final String INTENT_FLAG_JUMP_CODE = "JUMP_CODE";

    /**
     * 发送
     */
    public static final int SEND = 1;

    /**
     * 涂鸦
     */
    public static final int GRAFF = 2;

    /**
     * p1p
     */
    public static final int PAT_PAT = 3;

    private ViewPager mViewPager;

    public List<String> imageUrls;

    public String strCurrentUrl;

    private int index = 0;

    public ImagePagerAdapter adapter;

    private TextView tvTip;

    private ScanImageBottom scanImageBottom;

    private ScanImageTitle scanImageTitle;

    private boolean titleCanShow = true;

    private boolean bottomCanShow = true;

    public boolean isShowRight;// 是否需要显示右边菜单

    private int jumpCode;

    private int type;

    private int action;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getStrCurrentUrl() {
        return strCurrentUrl;
    }

    public void setStrCurrentUrl(String strCurrentUrl) {
        this.strCurrentUrl = strCurrentUrl;
    }

    @Override
    protected void preCreate() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

    }

    @Override
    public int setView() {
        return R.layout.activity_scan_image;
    }

    @Override
    public void findViews() {
        mViewPager = (ViewPager) findViewById(R.id.viewer);
        tvTip = (TextView) findViewById(R.id.scan_img_tip);
        scanImageBottom = (ScanImageBottom) findViewById(
                R.id.send_graff_layout);
        scanImageTitle = (ScanImageTitle) findViewById(
                R.id.see_photo_title_container);
    }

    /**
     * 点击按钮
     *
     * @author res-jxliu
     */
    private ViewOnClickListener myImageOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            dealClick(v);
        }
    };

    /**
     * 处理点击事件
     *
     * @param v view
     */
    private void dealClick(View v) {
        int vId = v.getId();

        if (vId == R.id.scan_img_graff) {
            // if (mCurBitmap != null)
            // {
            Intent intentGraff = new Intent();
            intentGraff.putExtra(IMAGE_URLS,
                    imageUrls.get(adapter.getCurrentPosition()));
            intentGraff.putExtra(INTENT_FLAG_TYPE, GRAFF);
            setResult(RESULT_OK, intentGraff);
            stopAction();
            // }
            // else
            // {
            // showToastError(R.string.null_photo);
            // }
        } else if (vId == R.id.scan_img_send) {
            // if (mCurBitmap != null)
            // {
            Intent intentSend = new Intent();
            intentSend.putExtra(IMAGE_URLS,
                    imageUrls.get(adapter.getCurrentPosition()));
            intentSend.putExtra(INTENT_FLAG_TYPE, SEND);
            setResult(RESULT_OK, intentSend);
            stopAction();
            // }
            // else
            // {
            // showToastError(R.string.null_photo);
            // }
        }

    }

    @Override
    public void initEvent() {

        findViewById(R.id.scan_img_close)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        findViewById(R.id.scan_img_menu)
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // showMenu();
                    }
                });
        View view = findViewById(R.id.scan_img_graff);
        if (view != null) {
            // 发送
            findViewById(R.id.scan_img_send)
                    .setOnClickListener(myImageOnClickListener);
            // 涂鸦
            view.setOnClickListener(myImageOnClickListener);
            // 拍一拍
            findViewById(R.id.scan_img_p1p)
                    .setOnClickListener(myImageOnClickListener);
        }

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (imageUrls.size() > 1) {
                    tvTip.setText(position + 1 + "/" + imageUrls.size());
                    // CWLog.e("debug", "测试图片数量dd：" + imageUrls.size());
                    adapter.setCurrentPosition(position);
                    setStrCurrentUrl(imageUrls.get(position));
                    setIndex(position);
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void init() {
        Log.i("curTime",
                System.currentTimeMillis() + "ScanImageActivity_initStart");
        hideTitleBar();
        setUseCommonBG(false);
        Intent mIntent = getIntent();
        if (mIntent != null) {
            jumpCode = mIntent.getIntExtra(INTENT_FLAG_JUMP_CODE,
                    JumpCode.JUMP_CODE_IMAGE);
            type = mIntent.getIntExtra(BaseIntentFlag.INTENT_FLAG_TYPE,
                    BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_TOP);
            action = mIntent.getIntExtra(BaseIntentFlag.INTENT_FLAG_ACTION, 0);
            imageUrls = mIntent
                    .getStringArrayListExtra(BaseJumpManager.IMAGE_URLS);
            index = mIntent.getIntExtra(BaseJumpManager.CURRENT_INDEX, 0);
            isShowRight = mIntent.getBooleanExtra(BaseJumpManager.IS_SHOWRIGHT,
                    false);

            if (jumpCode == JumpCode.JUMP_CODE_IMAGE) {
                if (imageUrls != null && imageUrls.size() != 0) {
                    tvTip.setText(index + 1 + "/" + imageUrls.size());
                }
            } else if (jumpCode == JumpCode.JUMP_CODE_GRAFF) {
                BaseJumpManager.jumpToSysAlbum(this, JumpCode.JUMP_CODE_GRAFF);
            } else if (jumpCode == JumpCode.JUMP_CODE_TAKE_PHOTO) {
                BaseJumpManager.jumpToCamera(this, R.string.go_back,
                        JumpCode.JUMP_CODE_TAKE_PHOTO);
            }

            delType();
        }
        if (imageUrls != null && !imageUrls.isEmpty()) {
            tvTip.setText(index + 1 + "/" + imageUrls.size());
            setStrCurrentUrl(imageUrls.get(index));
            setIndex(index);
        }
        if (isShowRight) {
            setRightBtnBG(getResources().getDrawable(R.mipmap.icon_del_nomal));
        }
        // 初始化画廊
        initViewPager();
    }

    /**
     * 控制显示
     */
    private void delType() {
        if (type == BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_TOP) {

            scanImageBottom.initHide();
            scanImageBottom.setVisibility(View.GONE);
            bottomCanShow = false;
        } else if (type == BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_BOTTOM) {
            CWLog.e("", "");
            scanImageTitle.initHide();
            scanImageTitle.setVisibility(View.GONE);
            titleCanShow = false;
        } else if (type == BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_ALL) {
            CWLog.e("", "");
        } else if (type == BaseIntentValue.ScanImgDisplayType.JUMP_TYPE_NO) {
            scanImageBottom.initHide();
            scanImageBottom.setVisibility(View.GONE);
            tvTip.setVisibility(View.GONE);
            bottomCanShow = false;
        }
    }

    @Override
    public void loadData() {

    }

    private void initViewPager() {
        if (imageUrls == null) {
            imageUrls = new ArrayList<String>();
        }
        final int limit = 3;
        adapter = new ImagePagerAdapter(this, imageUrls);
        mViewPager.setOffscreenPageLimit(limit);
        mViewPager.setAdapter(adapter);
        if (imageUrls.size() > index) {
            mViewPager.setCurrentItem(index);
            adapter.setCurrentPosition(index);
        }
    }

    /**
     * 获得当前图片的地址
     *
     * @return 如果是网络图片那么返回缓存地址，如果是本地图片那么返回本地地址
     */
    public String getCurrentImagePath() {
        String url = null;
        if (imageUrls.size() > adapter.getCurrentPosition()) {
            url = imageUrls.get(adapter.getCurrentPosition());
        } else {
            return "";
        }
        if (URLUtil.isHttpUrl(url) || URLUtil.isHttpsUrl(url)) {
            url = ImageLoaderHelper.getInstance().getImageCachePath(url);
        }
        return url;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.recycle();
        }
    }

    /**
     * 跳转码
     *
     * @author res-jxliu
     */
    public static class JumpCode {
        /**
         * 跳转码，拍照
         */
        public static final int JUMP_CODE_TAKE_PHOTO = 1;

        /**
         * 跳转码，相册
         */
        public static final int JUMP_CODE_GRAFF = 2;

        /**
         * 跳转码，图片
         */
        public static final int JUMP_CODE_IMAGE = 3;
    }

    public void initEventForMattacher(final PhotoViewAttacher mAttacher) {
        mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                CWLog.i("-------", "-------");
//                if (scanImageBottom.isShow())
//                {
//                    scanImageBottom.hide();
//                }
//                else if (bottomCanShow)
//                {
//                    scanImageBottom.show();
//                }
                if (scanImageTitle.isShow()) {
                    scanImageTitle.hide();
                } else if (titleCanShow) {
                    scanImageTitle.show();
                }
                // handlerBottomView();
            }
        });

        mAttacher.setOnMatrixChangeListener(new OnMatrixChangedListener() {
            @Override
            public void onMatrixChanged(RectF rect) {
                float scale = mAttacher.getScale();
                if (scale < 0.5f) {
                    // Animation animation = AnimationUtils.loadAnimation(
                    // ScanImageActivity.this, R.anim.photo_zoom_out);
                    // mViewPager.startAnimation(animation);
                    finish();
                }
                // mViewPager.setAlpha(scale * 1.5f);
                if (mAttacher.getScale() == mAttacher.getMinScale()
                        && adapter.getCurrentPosition() == 0) {
                    // mViewPager.setFirstPage(true);
                } else {
                    // mViewPager.setFirstPage(false);
                }
            }
        });
    }

    ViewOnClickListener viewonclick = new ViewOnClickListener() {

        @Override
        public void avertRepeatOnClick(View v) {
            // if (v.getId() == R.id.line_scrawlcheck)
            // {
            //
            // }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == JumpCode.JUMP_CODE_TAKE_PHOTO) {
                String path = data
                        .getStringExtra(CameraActivity.PAHT_FLAG_PATH);
                imageUrls.add(path);
                // adapter.initImageViews(imageUrls.size());

                CWLog.e("debug", "拍照：" + imageUrls.size());
                adapter.setCurrentPosition(0);
                adapter.notifyDataSetChanged();
            } else if (requestCode == JumpCode.JUMP_CODE_GRAFF) {
                Uri uri = data.getData();
                String path = null;

                Cursor c = getContentResolver().query(uri,
                        new String[]{MediaStore.Images.Media.DATA}, null, null,
                        null);
                if (c != null && c.moveToNext()) {
                    path = c.getString(0);
                    c.close();
                } else {
                    path = uri.getPath();
                }
                FileUtils.delete(ImageLoaderHelper.getInstance()
                        .getImageCachePath(path));
                imageUrls.add(path);
                // adapter.initImageViews(imageUrls.size());
                CWLog.e("debug", "相册：" + imageUrls.size());
                adapter.setCurrentPosition(0);
                adapter.notifyDataSetChanged();
            }
        } else {
            finish();
        }
    }

    /**
     * 关闭
     */
    private void stopAction() {
        finish();
    }

}
